const defaultoption={
  quality:0.7,// 默认图片质量为0.7，效率高竞价比0.4
  mimeType:"image/jpeg",
}

const convertBase64UrlToBlob = (urlData) =>{
  const arr = urlData.split(',');
  const mime = arr[0].match(/:(.*?);/)[1];
  const bstr = atob(arr[1]);
  let n = bstr.length;
  const u8arr = new Uint8Array(n);
  while(n--){
      u8arr[n] = bstr.charCodeAt(n);
  }
  return new Blob([u8arr], {type:mime});
}

const canvasDataURL = (path, options) => {
  return new Promise((resolve, reject) => {
      try {
        const originalBlob = convertBase64UrlToBlob(path);
        const img = new Image();
        img.src = path;
        img.onload = () => {
          // 默认按比例压缩
          let w = img.width;
          let h = img.height;
          const scale = w / h;
          w = options.width || w;
          h = options.height || (w / scale);
          // 生成canvas
          const canvas = document.createElement('canvas');
          const ctx = canvas.getContext('2d');
          // 创建属性节点
          const anw = document.createAttribute("width");
          anw.nodeValue = w;
          const anh = document.createAttribute("height");
          anh.nodeValue = h;
          canvas.setAttributeNode(anw);
          canvas.setAttributeNode(anh);
          ctx.drawImage(img, 0, 0, w, h);
          
          // quality值越小，所绘制出的图像越模糊
          const base64 = canvas.toDataURL(originalBlob.type||defaultoption.mimeType, options.quality||defaultoption.quality);
          
          // 回调函数返回Blob对象
          const resultBlob = convertBase64UrlToBlob(base64);
          // callback(resultBlob.size<originalBlob?resultBlob:originalBlob);
          resolve(resultBlob.size<originalBlob?resultBlob:originalBlob)
      }
    } catch (e) {
      console.log("压缩图片报错")
      reject(false)
    }
  })

}

const photoCompress = (file,options={}) => {
  /* 开始读取指定的Blob对象或File对象中的内容. 当读取操作完成时,readyState属性的值会成为DONE,如果设置了onloadend事件处理程序,则调用之.同时,result属性中将包含一个data: URL格式的字符串以表示所读取文件的内容. */
  return new Promise((resolve, reject) => {
      const ready=new FileReader();
      ready.onload = () => {
        canvasDataURL(ready.result,options)
        .then((res)=>{
          resolve(res)
        }).catch(err=>{
            reject(err)
        })
      }
      ready.onerror = (event) => {
          ready.abort();
          reject(event)
        };
      ready.readAsDataURL(file);
  })
}

export default photoCompress;